<template>
  <Modal
    title="编辑"
    :value="value"
    :mask-closable="true"
    :footer-hide="true"
    @input="$emit('input', $event)"
  >
    <Form
      ref="formTest"
      :model="formTest"
      :rules="ruleValidate"
      label-position="right"
      :label-width="80"
    >
      <FormItem label="id" prop="id">
        <InputNumber v-model="formTest.id" placeholder=""/>
      </FormItem>
      <FormItem label="姓名" prop="name">
        <Input type="text" v-model="formTest.name" placeholder=""/>
      </FormItem>
      <FormItem label="年龄" prop="age">
        <InputNumber v-model="formTest.age" placeholder=""/>
      </FormItem>
      <FormItem>
        <Button type="primary" @click="handleSubmit('formTest')">提交</Button>
        <Button @click="handleReset('formTest')" style="margin-left: 8px">重置</Button>
      </FormItem>
    </Form>
  </Modal>
</template>
<script>
  import { update } from '@/api/test'
  import { createModelObj, coverProps, coverFormProps } from '@/libs/util'

  export default {
    name: 'Edit',
    props: {
      value: {
        type: Boolean,
        default: false
      },
      test: {
        type: Object,
        default: null
      }
    },
    data () {
      return {
        formTest: {

          id: 0
          ,
          name: ''
          ,
          age: 0
        },
        ruleValidate: {

          id: [
            { type: 'number', max: 9999999999, message: '最大为9999999999', trigger: 'blur' }
          ]
          ,
          name: [
            { required: false, message: '该值不能为空', trigger: 'blur' },
            { type: 'string', max: 255, message: '长度最长为255', trigger: 'blur' }
          ]
          ,
          age: [
            { type: 'number', max: 9999999999, message: '最大为9999999999', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      handleSubmit (name) {
        this.$refs[name].validate(valid => {
          if (valid) {
            update(
              Object.assign({}, createModelObj(this.formTest, 'test'))
            ).then(res => {
              if (res) {
                this.$emit('updateRow', coverProps(this.test, this.formTest))
                this.$emit('input', false)
                this.handleReset(name)
              }
            })
          } else {
            this.$Message.error('验证失败!')
          }
        })
      },
      handleReset (name) {
        this.$refs[name].resetFields()
      }
    },
    watch: {
      value: function (val, oldVal) {
        this.$refs.formTest.resetFields()
        coverFormProps(this.formTest, this.test)
      }
    }
  }
</script>
